#include "BatteryModule.h"

bool BatteryModule::init() {
	//UART Init
	Serial.begin(115200);
	Serial.println("Battery Module init...");

	//GPIO Init
	pinMode(LED1 | LED2 | LED3, INPUT);

	//ADC Init
	adc1_config_width(ADC_WIDTH_BIT_12);
	//Set ADC Channel 1 GPIO 36; Attenuation 11dB 3.6;
	//At 11dB attenuation the maximum voltage is limited by VDD_A(3.3V), not the full scale voltage.
	adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_DB_11);
}

int BatteryModule::getADC() {	
	return adc1_get_raw(ADC1_CHANNEL_0);
}

uint16_t BatteryModule::getADCAverage() {
	if (getVoltageMode == GetBatteryByADC) {
		uint8_t i = 0;
		uint32_t adcTotal = 0;
		for (i = 0; i < ADC_CALCULATE_ROUND; i++) {
			adcTotal = adcTotal + getADC();
			delay(10);
		}
		return(adcTotal / ADC_CALCULATE_ROUND);
	}
}

uint8_t BatteryModule::getBatteryPercent() {
	uint8_t batteryPercent = 0;
	uint16_t adcAverage = getADCAverage();
	if (adcAverage > Percent100Point) {
		adcAverage = 100;
	}
	else
	{
		batteryPercent = (getADCAverage() - Percent0Point) * 100 / (Percent100Point - Percent0Point);
	}
	return batteryPercent;
}

uint8_t BatteryModule::getLED() {
	int LED1Cnt = 0;
	int LED2Cnt = 0;
	int LED3Cnt = 0;
	int i = 0;
	int t = 0;
	uint8_t pwr = 0;
	LED1Cnt = 0;
	LED2Cnt = 0;
	LED3Cnt = 0;
	for (i = 0; i<500; i++) {
		t = digitalRead(LED1);
		if (t>0) {
			LED1Cnt++;
		}

		t = digitalRead(LED2);
		if (t>0) {
			LED2Cnt++;
		}

		t = digitalRead(LED3);
		if (t>0) {
			LED3Cnt++;
		}
		t = 0;
		delay(1);
	}


	if (LED1Cnt >= 200 && LED2Cnt >= 200 && LED3Cnt >= 200) {
		pwr = 100;
	}
	else if (LED1Cnt < 200 && LED2Cnt > 200 && LED3Cnt < 200) {
		pwr = 75;
	}
	else if (LED1Cnt <= 200 && LED2Cnt>=100 && LED2Cnt <= 200 && LED3Cnt>=100 && LED3Cnt < 200) {
		pwr = 50;
	}
	else if (LED1Cnt < 200 && LED2Cnt < 100 && LED3Cnt < 100) {
		pwr = 25;
	}
	else {
		pwr = 0;
	}
	//Serial.println("LED Read Battery:");
	//Serial.println(pwr);
	//Serial.println("----------------------");
	return pwr;

}